package com.example.kafka.metric;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lingGao
 */
@Component
@Slf4j
public class HostReader {

    private static final String[] HOST_FILE_LOCATIONS = new String[]{"classpath:host/host.xls"};

    private volatile List<HostData> hostDataList;

    public List<HostData> getHostDataList() throws Exception {
        if (hostDataList == null) {
            synchronized (HostReader.class) {
                if (hostDataList == null) {
                    List<HostData> hostDataList = new ArrayList<>(105020);
                    DefaultResourceLoader resourceLoader = new DefaultResourceLoader(HostReader.class.getClassLoader());
                    for (String hostFileLocation : HOST_FILE_LOCATIONS) {
                        Resource resource = resourceLoader.getResource(hostFileLocation);
                        EasyExcel.read(resource.getInputStream(), HostData.class, new ReadListener<HostData>() {

                            @Override
                            public void invoke(HostData hostData, AnalysisContext analysisContext) {
                                hostDataList.add(hostData);
                            }

                            @Override
                            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                                log.info("read {} host data", hostDataList.size());
                            }
                        }).sheet(0).doRead();
                    }
                    this.hostDataList = hostDataList;
                }
            }
        }
        return this.hostDataList;
    }

}
